<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="root"></div>
    <script>
        // 事件循环机制的思考
        let root = document.querySelector('#root');
        let i = 0;

        let start = Date.now();
        function app() {
            setTimeout(() => {
                console.log("1-1");
                do {
                    i++;
                } while (i % 1e8 != 0);
                root.innerHTML = "he"
                // Promise.resolve().then(() => {

                //     console.log("2-1");
                //     do {
                //         i++;
                //     } while (i % 1e8 != 0);
                //     root.innerHTML = "it"
                // });
            });
            console.log("1-2");
            root.innerHTML = "me"
            Promise.resolve().then(() => {
                console.log("1-3");
                do {
                    i++;
                } while (i % 1e8 != 0);
                root.innerHTML = "her"
                Promise.resolve().then(() => {
                    console.log("3-1");
                    do {
                        i++;
                    } while (i % 1e8 != 0);
                    root.innerHTML = "they"
                });
            });
        }
        app();




        function count() {
            console.log(i)
            // 做繁重的任务的一部分 (*)
            do {
                i++;
            } while (i % 1e6 != 0);

            if (i == 1e9) {
                alert("Done in " + (Date.now() - start) + 'ms');
            } else {
                setTimeout(count); // 安排（schedule）新的调用 (**)
            }

        }

        function count2() {

            // 做一个繁重的任务
            for (let j = 0; j < 1e9; j++) {
                i++;
            }

            alert("Done in " + (Date.now() - start) + 'ms');
        }

        function count3() {
            console.log(i)
            // 将调度（scheduling）移动到开头
            if (i < 1e9 - 1e6) {
                setTimeout(count3); // 安排（schedule）新的调用
            }

            do {
                i++;
            } while (i % 1e6 != 0);

            if (i == 1e9) {
                alert("Done in " + (Date.now() - start) + 'ms');
            }

        }


        function count4() {
            for (let i = 0; i < 1e4; i++) {
                i++;
                console.log(i)
                root.innerHTML = i;
            }
        }

        function count5() {
            console.log(i)
            // 做繁重的任务的一部分 (*)
            do {
                i++;
                root.innerHTML = i;
            } while (i % 1e3 != 0);

            if (i < 1e7) {
                setTimeout(count5);
            }

        }
        // count5();
    </script>
</body>

</html>